package com.lib.common.base.web

import android.app.Application
import android.os.Build
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import com.lib.common.base.mvvm.CommonFragmentViewModel
import com.lib.common.base.web.bridge.JsToNativeBridge
import com.lib.common.base.web.bridge.JsToNativeBridgeMethodHelper
import com.lib.framework.R
import wendu.dsbridge.CompletionHandler

/**
 * 基本网页 Fragment 的 ViewModel
 *
 * @author keanbin
 */
abstract class BaseWebViewModel(application: Application) : CommonFragmentViewModel(application) {

    /**
     * 加载的网址
     */
    var mLoadUrl: String? = null

    /**
     * 网页当前的url
     */
    var mCurrentUrl: String? = null

    /**
     * js 主动调用 原生的 桥接 方法 管理对象
     */
    val mJsToNativeBridgeMethodHelper = JsToNativeBridgeMethodHelper()

    /**
     * js 主动调用 原生的 桥接 对象
     */
    val mJsToNativeBridge = JsToNativeBridge(mJsToNativeBridgeMethodHelper)

    /**
     * 加载网页
     */
    fun loadUrl(url: String) {
        mLoadUrl = url
        sendEvent(BaseWebFragment.EVENT_LOAD_URL, url)
    }

    /**
     * 重新载入
     */
    fun reload() {
        sendEvent(BaseWebFragment.EVENT_RELOAD)
    }

    /**
     *  桥接：增加方法
     */
    fun addMethodOfBridge(methodName: String,
                          method: (msg: Any, handler: CompletionHandler<String?>) -> Unit) {
        mJsToNativeBridgeMethodHelper.addMethod(methodName, method)
    }

    /**
     *  桥接：缓存 CompletionHandler
     */
    fun addCompletionHandlerToCacheOfBridge(methodName: String,
                                            handler: CompletionHandler<String?>) {
        mJsToNativeBridgeMethodHelper.addCompletionHandlerToCache(methodName, handler)
    }

    /**
     * 桥接：从缓存获取 CompletionHandler，并从缓存删除该 CompletionHandler
     */
    fun getCompletionHandlerFromCachOfBridge(methodName: String): CompletionHandler<String?>? {
        return mJsToNativeBridgeMethodHelper.getCompletionHandlerFromCache(methodName)
    }

    /**
     * 网页标题发生改变
     */
    open fun onChangePageTitle(title: String) {

    }

    /**
     * 页面出错
     */
    open fun onPageError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) {
        if (needShowErrorView(view, error)) {
            sendEvent(BaseWebFragment.EVENT_SHOW_ERROR_VIEW)
        }
    }

    /**
     * 是否需要显示错误提示页面
     */
    open fun needShowErrorView(view: WebView?, error: WebResourceError?): Boolean {
        if (Build.VERSION.SDK_INT >= 23) {
            when (error?.errorCode) {
                WebViewClient.ERROR_HOST_LOOKUP -> {
                    val title = view?.title ?: ""
                    return title.contains(mContext.getString(R.string.pageNotFound), true) || title.contains(mContext.getString(R.string.unableOpenUrl), true) || title.isEmpty() || title.contains("404") || title.contains("500") || title.contains("Error", true)
                }

                WebViewClient.ERROR_AUTHENTICATION, WebViewClient.ERROR_BAD_URL,
                    //WebViewClient.ERROR_CONNECT,
                WebViewClient.ERROR_FAILED_SSL_HANDSHAKE, WebViewClient.ERROR_FILE, WebViewClient.ERROR_FILE_NOT_FOUND, WebViewClient.ERROR_HOST_LOOKUP, WebViewClient.ERROR_IO, WebViewClient.ERROR_PROXY_AUTHENTICATION, WebViewClient.ERROR_REDIRECT_LOOP, WebViewClient.ERROR_TIMEOUT, WebViewClient.ERROR_TOO_MANY_REQUESTS,
                    //WebViewClient.ERROR_UNKNOWN, WebViewClient.ERROR_UNSUPPORTED_SCHEME,
                WebViewClient.ERROR_UNSUPPORTED_AUTH_SCHEME -> {
                    return true
                }
            }
        }

        return false
    }

    /**
     * 开始加载网页
     */
    abstract fun startLoadUrl()
}
